package cn.iocoder.ny.module.mall.annotation;
import cn.iocoder.ny.module.mall.config.MallProperties;
import cn.iocoder.ny.module.mall.utils.EncryptionConstants;
import cn.iocoder.ny.module.mall.utils.EncryptionUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

@ControllerAdvice
public class DecryptRequest extends RequestBodyAdviceAdapter {



    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
        inputMessage.getBody().read(body);

        try {
            if (MallProperties.ENCRYPTED){
                byte[] decrypt = EncryptionUtil.decryptWithAES(body, EncryptionConstants.MALL).getBytes();
                final ByteArrayInputStream bais = new ByteArrayInputStream(decrypt); // 再将字节转为输入流
                return new HttpInputMessage() {
                    @Override
                    public InputStream getBody() throws IOException {
                        return bais;  // 再将输入流返回
                    }
                    @Override
                    public HttpHeaders getHeaders() {
                        return inputMessage.getHeaders();
                    }
                };
            }else {
                byte[] decrypt = body;
                final ByteArrayInputStream bais = new ByteArrayInputStream(decrypt); // 再将字节转为输入流
                return new HttpInputMessage() {
                    @Override
                    public InputStream getBody() throws IOException {
                        return bais;  // 再将输入流返回
                    }
                    @Override
                    public HttpHeaders getHeaders() {
                        return inputMessage.getHeaders();
                    }
                };
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}